<template>
    <div>
        <div class="container1">
            <div class="common-title-flex">
                <div class="common-title-div"></div>
                <div class="common-title-text">驻厂代表查询条件</div>
            </div>
            <el-form ref="searchObj" :inline="true" :model="searchObj" size="mini" label-width="80px" style="margin-bottom:-10px;margin-top:10px;">
                    <el-form-item label="姓名">
                        <el-input v-model="searchObj.name" placeholder="请输入姓名" clearable ></el-input>
                    </el-form-item>
                    <el-form-item label="身份证号">
                        <el-input v-model="searchObj.identity" placeholder="请输入身份证号" clearable ></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码">
                        <el-input v-model="searchObj.phone" placeholder="请输入手机号码" clearable ></el-input>
                    </el-form-item>
                    <el-form-item style="margin-left:2rem;">
                        <el-button type="primary" icon="el-icon-search" @click="query">查询</el-button>
                        <el-button @click="reset" icon="el-icon-refresh">重置</el-button>
                    </el-form-item>
            </el-form>
        </div>
        <div class="container" style="margin-top:1rem;">
            <div class="common-list-class">
                <div style="display:flex;">
                    <div class="common-title-div"></div>
                    <div class="common-title-text">驻厂代表查询列表</div>
                </div>
                <div style="display:flex;">
                    <!-- <el-upload
                    class="upload-file"
                    :headers="uploadHeader"
                    :before-upload="beforeUpload"
                    :action="uploadUrl"
                    :on-success="uploadSucess"
                    :on-error="uploadError"
                    :on-progress="uploadProgress"
                    :show-file-list="false">
                        <el-button type="primary" icon="el-icon-download">批量导入</el-button>
                    </el-upload>
                    <el-button type="primary" style="height:32px;margin-left:10px;" icon="el-icon-upload">模版下载</el-button> -->
                    <el-button type="primary" style="height:32px;" icon="el-icon-upload2" @click="alldaochuClick">批量导出</el-button>
                    <el-button type="primary" style="height:32px;" v-if="roleCode == 'labourBusinessManage'" icon="el-icon-circle-plus-outline" @click="addPolice">添加</el-button>
                </div>
            </div>
            <!-- 查询列表 -->
            <el-table :data="tableData" size="mini" :row-style="rowStyle" @sort-change="sortChange" @cell-click="cellChange" :header-cell-style="tableHeaderColor" style="width: 100%;margin-top:10px;margin-bottom:10px;" max-height="550" border>
                <el-table-column prop="name" label="姓名"   show-overflow-tooltip align="center">
                </el-table-column>
                <el-table-column prop="componentName" label="服务企业"  show-overflow-tooltip align="center">
                </el-table-column>
                <el-table-column prop="employeeNum" label="劳务工人数" sortable show-overflow-tooltip align="center">
                    <template slot-scope="scope">
                        <div style="cursor: pointer;">
                            {{scope.row.employeeNum}}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间"  show-overflow-tooltip align="center">
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100"  show-overflow-tooltip align="center">
                    <template slot-scope="scope">
                        {{statusObj[scope.row.status]}}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="300" align="center">
                    <template slot-scope="scope">
                        <!-- <el-button type="primary" size="mini" icon="el-icon-edit" @click.stop="editClick(scope.row)">修改</el-button> -->
                        <el-button type="success" size="mini" icon="el-icon-video-play" v-if="scope.row.status == '0'" @click.stop="startClick(scope.row)">启用</el-button>
                        <el-button type="danger" size="mini" icon="el-icon-remove" v-if="scope.row.status == '1'" @click.stop="forbidClick(scope.row)">停用</el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" @click.stop="deleteClick1(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-row type="flex" justify="end">
                    <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="pageSizes"
                    :page-size="pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                    </el-pagination>
            </el-row>
        </div>
        <!-- 新增驻厂代表 -->
        <el-dialog title="新增驻厂代表" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="newaddFlag" width="55%" :before-close="cancel" center>
            <div slot="title" class="header-title">
                <div class="header-title-div"></div>
                <div class="header-title-text">新增驻厂代表</div>
            </div>
            <el-form ref="inputObj" :model="inputObj" label-width="100px" :rules="rules">
                    <el-divider>账户信息</el-divider>
                    <el-form-item label="账号名称" prop="accountName">
                        <el-tooltip class="item" effect="dark" content="账号格式：大小写字母或数字" placement="top-start">
                            <el-input v-model="inputObj.accountName" placeholder="请输入账户名称" clearable ></el-input>
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-tooltip class="item" effect="dark" content="密码格式：大小写字母或数字" placement="top-start">
                            <el-input v-model="inputObj.password" placeholder="请输入密码" clearable show-password></el-input>
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickName">
                        <el-input v-model="inputObj.nickName" maxlength="30" placeholder="请输入昵称" clearable ></el-input>
                    </el-form-item>
                    <el-divider>驻厂代表信息</el-divider>
                    <!-- <el-form-item label="姓名" prop="name">
                        <el-input v-model="inputObj.name" placeholder="请输入姓名" clearable ></el-input>
                    </el-form-item>
                    <el-form-item label="电话" prop="phone">
                        <el-input v-model="inputObj.phone" placeholder="请输入电话" clearable ></el-input>
                    </el-form-item>
                    <el-form-item label="身份证" prop="identity">
                        <el-input v-model="inputObj.identity" placeholder="请输入身份证" clearable ></el-input>
                    </el-form-item> -->
                    <el-form-item label="服务公司" prop="descOrgCode">
                        <el-select v-model="inputObj.descOrgCode" size="mini" placeholder="请选择服务公司" @change="descOrgCodeChange" style="width:100%;">
                            <el-option
                            v-for="item in bindingList"
                            :key="item.ORG_CODE"
                            :label="item.COMPANY_NAME"
                            :value="item.ORG_CODE">
                            </el-option>
                        </el-select>
                    </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submit">提 交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </span>
        </el-dialog>

        <!-- <el-dialog title="修改驻厂代表" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="editFlag" width="55%" :before-close="cancel1" center>
            <div slot="title" class="header-title">
                <div class="header-title-div"></div>
                <div class="header-title-text">修改驻厂代表</div>
            </div>
            <el-form ref="inputObj1" :model="inputObj1" label-width="100px" :rules="rules1">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="inputObj1.name" placeholder="请输入姓名" clearable ></el-input>
                    </el-form-item>
                    <el-form-item label="电话" prop="phone">
                        <el-input v-model="inputObj1.phone" placeholder="请输入电话" clearable ></el-input>
                    </el-form-item>
                    <el-form-item label="身份证" prop="identity">
                        <el-input v-model="inputObj1.identity" placeholder="请输入身份证" clearable ></el-input>
                    </el-form-item>
                    <el-form-item label="服务公司" class="required-content-red">
                            <el-transfer
                            filterable
                            :titles="['未绑定公司', '已绑定公司']"
                            filter-placeholder="请输入公司名称"
                            v-model="bindValue"
                            :data="bindingList">
                        </el-transfer>
                    </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submit1">提 交</el-button>
                <el-button @click="cancel1">取 消</el-button>
            </span>
        </el-dialog> -->
        <!-- 警员详情 -->
        <el-dialog title="驻厂代表详情" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="detailsFlag" width="40%" :before-close="detailsClose" center>
            <div slot="title" class="header-title">
                <div class="header-title-div"></div>
                <div class="header-title-text">驻厂代表详情</div>
            </div>
            <el-row type="flex" justify="center">
                <el-col :span="4" class="bold-class">姓名</el-col>
                <el-col :span="15" class="grey-class">{{detailsObj.representName}}</el-col>
            </el-row>
            <el-row type="flex" justify="center">
                <el-col :span="4" class="bold-class">公司编号</el-col>
                <el-col :span="15" class="grey-class">{{detailsObj.companyCode}}</el-col>
            </el-row>
            <el-row type="flex" justify="center">
                <el-col :span="4" class="bold-class">电话</el-col>
                <el-col :span="15" class="grey-class">{{detailsObj.phone}}</el-col>
            </el-row>
            <el-row type="flex" justify="center">
                <el-col :span="4" class="bold-class">身份证号</el-col>
                <el-col :span="15" class="grey-class">{{detailsObj.identityCode}}</el-col>
            </el-row>
            <el-row type="flex" justify="center">
                <el-col :span="4" class="bold-class">现住地</el-col>
                <el-col :span="15" class="grey-class">{{detailsObj.currentResidence}}</el-col>
            </el-row>
            <el-row type="flex" justify="center">
                <el-col :span="4" class="bold-class">户籍地</el-col>
                <el-col :span="15" class="grey-class">{{detailsObj.domicile}}</el-col>
            </el-row>
            <el-row type="flex" justify="center">
                <el-col :span="4" class="bold-class">状态</el-col>
                <el-col :span="15" class="grey-class">{{detailsObj.status}}</el-col>
            </el-row>
            <el-row type="flex" justify="center">
                <el-col :span="4" class="bold-class">创建时间</el-col>
                <el-col :span="15" class="grey-class">{{detailsObj.createTime}}</el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button type="danger" @click="detailsClose">关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import mixin from '@/mixin/mixin.js'; 
    export default {
        name: 'representativeManage',
        mixins: [mixin],
        data(){
            const self = this;
            return {
                statusObj:{
                    '0':'已停用',
                    '1':'已启用'
                },
                bindingList: [],
                uploadHeader:{},
                rules:{
                    descOrgCode:[
                       { required: true, message: '请选择服务公司', trigger: 'change' }
                    ],
                    accountName:[
                        { required: true, message: '请输入账号名称', trigger: 'blur' },
                        {
                            validator: (rule, value, callback) => {
                                if (!(/^[0-9a-zA-Z]+$/).test(value.trim())) {
                                    callback(new Error('账号名称格式错误！'));
                                } else {
                                    self.$axios({
                                        method: 'get',
                                        url: `/system/validateAccountExist/${value.trim()}`,
                                        headers:{
                                            Authorization: this.requestToken   
                                        },
                                    }).then(res => {
                                        console.log(res.data)
                                        if(res.data.code == '20000' && res.data.data){
                                            callback()
                                        }else{
                                            self.inputObj.accountName = '';
                                            callback(new Error('账号已存在！请重新输入！'));
                                        }
                                    }).catch(err => {
                                        callback(new Error(err));
                                    })
                                }
                            },
                            trigger: 'blur'
                        }
                    ],
                    password:[
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        {
                            validator: (rule, value, callback) => {
                            if (!(/^[0-9a-zA-Z]+$/).test(value.trim())) {
                                callback(new Error('密码格式错误！'));
                            } else {
                                callback()
                            }
                            },
                            trigger: 'blur'
                        }
                    ],
                    nickName: [
                        { required: true, message: '请输入昵称', trigger: 'blur' }
                    ],
                },
                bindingFlag:false,
                detailsObj:{
                    representName:'张三',
                    companyCode:'12300000',
                    phone:'1391229223',
                    identityCode:'3206821996837383',
                    currentResidence:'江苏南京',
                    status:'已启用',
                    domicile:'江苏南通',
                    createTime:'2020-12-20'
                },
                inputObj:{},
                inputObj1:{},
                editFlag:false,
                detailsFlag:false,
                isEditTitle:'',
                newaddFlag:false,
                pageSizes:[10, 15, 50, 100],
                pagesize:10,
                total:10,
                currentPage:1,
                tableData: [],
                searchObj:{
                    representName:'',
                    representCode:'',
                    identityCode:'',
                    descFlag:1
                }
            }
        },
        created(){
           this.query();
        },
        methods: {
            descOrgCodeChange(value){
                this.$forceUpdate();
                let self = this;
                self.bindingList.forEach((item)=>{
                    if(item.ORG_CODE == value){
                        self.inputObj.descCompanyName = item.COMPANY_NAME
                    }
                })
            },
            sortChange({ column, prop, order }){
                if(column.label == '劳务工人数'){
                    if(order == 'ascending'){
                        console.log('正序')
                        this.searchObj.descFlag = 0;
                        this.query();
                    }else if(order == 'descending'){
                        this.searchObj.descFlag = 1;
                        this.query();
                        console.log('倒序')
                    }
                }
            },
            cellChange(row, column, cell, event){
                let labourName = row.labourName;
                if(column.label == "劳务工人数"){
                    this.$router.push({ name: 'allPerson', params: { labourName: row.labourName,status:'在职人员' }})
                }
            },
            // 删除
            deleteClick1(row){
                this.$confirm('请确认是否删除该驻厂代表数据?', '删除', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    }).then(() => {
                        this.showLoading();
                        this.$axios({
                            method: 'delete',
                            url: `/site/deleteById/${row.id}`,
                            headers:{
                                Authorization:this.requestToken     
                            },
                        }).then(res => {
                            this.hideLoading();
                            if(res.data.code == '20000'){
                                this.$message.success('删除成功！');
                                this.query();
                            }else{
                                this.$message.error(res.data.message)
                            }
                        }).catch(err => {
                            this.hideLoading();
                            this.$message.error(err)
                        })
                    }).catch(() => {
                        console.log('取消删除')       
                    });
            },
            beforeUpload(file){
                this.showLoading('导入中')
            },
            uploadProgress(event, file, fileList){
                console.log('event--------',event)
                console.log('file--------',file)
                console.log('fileList--------',fileList)
            },
            uploadSucess(response){
                this.$message({
                    message:'导入成功！',
                    type:'success'
                })
                this.hideLoading();
                console.log('response------',response)
            },
            uploadError(error){
                 this.$message({
                    message:'导入失败！',
                    type:'error'
                })
                this.hideLoading();
                console.log('error-----',error)
            },
            submit1(){
                let self = this;
                this.$refs['inputObj1'].validate((valid) => {
                    if (valid) {
                            if(!self.bindValue || !self.bindValue.length){
                                self.$message.error('请选择服务企业！')
                                return;
                            }
                            let params = self.inputObj1;
                            params.id = self.currentId;
                            params.userId = self.currentUserid;
                            params.componentCodes = self.bindValue;
                            self.showLoading();
                            self.$axios({
                                method: 'post',
                                url: `/site/editLabourSiteInfos`,
                                headers:{
                                    Authorization:self.requestToken     
                                },
                                data: params
                            }).then(res=>{
                                self.hideLoading();
                                if(res.data.code == '20000'){
                                    self.$message.success('修改成功！');
                                    self.editFlag = false;
                                    self.inputObj1 = {};
                                    self.$refs["inputObj1"].resetFields();
                                    self.bindValue = [];
                                    self.query();
                                }else{
                                    self.$message.error(res.data.message)
                                }
                            }).catch(err=>{
                                self.hideLoading();
                                self.$message.error(err)
                            })
                    } else {
                        return false;
                    }
                });
            },
            cancel1(){
                this.inputObj1 = {};
                this.$refs["inputObj1"].resetFields();
                this.bindValue = [];
                this.editFlag = false;
            },
            cancel(){
                this.inputObj = {};
                this.$refs["inputObj"].resetFields();
                this.bindValue = [];
                this.newaddFlag = false;
            },
            // 新建确认和修改确认
            submit(){
                let self = this;
                this.$refs['inputObj'].validate((valid) => {
                    if (valid) {
                            let params = self.inputObj;
                            self.showLoading();
                            self.$axios({
                                method: 'post',
                                url: `/site/addLabourSiteInfos`,
                                headers:{
                                    Authorization:self.requestToken     
                                },
                                data: params,
                            }).then(res=>{
                                self.hideLoading();
                                if(res.data.code == '20000'){
                                    self.$message.success('新增成功！');
                                    self.newaddFlag = false;
                                    self.inputObj = {};
                                    self.$refs["inputObj"].resetFields();
                                    self.bindValue = [];
                                    self.query();
                                }else{
                                    self.$message.error(res.data.message)
                                }
                            }).catch(err=>{
                                self.hideLoading();
                                self.$message.error(err)
                            })
                    } else {
                        return false;
                    }
                });
            },
            tableHeaderColor({row,column,rowIndex,columnIndex}){
                return 'background-color:#f5f5f5;color:#626262;'
            },
            rowStyle({ row, rowIndex}){
                let style1={};
                let style2={};
                if(rowIndex%2 == 0){
                    style1.background = '#ffffff';
                    return style1
                }else{
                    style2.background = '#f5f5f5';
                    return style2
                }
            },
            // 点击分页当前页多少数据
            handleSizeChange(val){
                this.pagesize = val;
                this.query();
            },
            // 点击分页页数
            handleCurrentChange(val){
                this.currentPage = val;
                this.query();
            },
            // 启用
            startClick(row){
                let self = this;
                this.$confirm('请确认是否启用该驻厂代表?', '启用', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                }).then(() => {
                    self.showLoading();
                    self.$axios({
                        method: 'get',
                        url: `/site/editOpenStatus/${row.userId}/1`,
                        headers:{
                            Authorization:self.requestToken     
                        }
                    }).then(res => {
                        self.hideLoading();
                        if(res.data.code == '20000'){
                            self.$message.success('启用成功！');
                            self.query();
                        }else{
                            self.$message.error(res.data.message)
                        }
                    }).catch(err => {
                        self.hideLoading();
                        self.$message.error(err)
                    })
                }).catch(() => {
                    self.$message({
                        type: 'info',
                        message: '已取消启用'
                    });          
                });
            },
            // 查询
            query() {
                let params = {
                  labourName:this.searchObj.representName,
                  pageNumber:this.currentPage,
                  pageSize:this.pagesize,
                  phone:this.searchObj.phone,
                  descFlag:this.searchObj.descFlag,
                  identityCode:this.searchObj.identityCode
              }
              this.showLoading();
              this.$axios({
                    method: 'post',
                    url: `/site/queryPageList`,
                    headers:{
                        Authorization:this.requestToken 
                    },
                    data: params,
                    params: params
                }).then(res => {
                    this.hideLoading();
                    console.log('res---->:',res);
                    if(res.data.code == '20000'){
                        this.tableData = res.data.data.list;
                        this.pagesize = res.data.data.pageSize;
                        this.total = res.data.data.total;
                    }else{
                        this.$message({
                            message:res.data.message,
                            type:'error'
                        })
                    }
                }).catch(err => {
                    this.hideLoading();
                    this.$message({
                        message:err,
                        type:'error'
                    })
                })
            },
            //  重置
            reset(){
                this.searchObj = {};
                this.query();
            },
            // 停用
            forbidClick(row){
                let self = this;
                this.$confirm('请确认是否停用该驻厂代表?', '停用', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                }).then(() => {
                    self.showLoading();
                    self.$axios({
                        method: 'get',
                        url: `/site/editOpenStatus/${row.userId}/0`,
                        headers:{
                            Authorization:self.requestToken     
                        }
                    }).then(res => {
                        self.hideLoading();
                        if(res.data.code == '20000'){
                            self.$message.success('停用成功！');
                            self.query();
                        }else{
                            self.$message.error(res.data.message)
                        }
                    }).catch(err => {
                        self.hideLoading();
                        self.$message.error(err)
                    })
                }).catch(() => {
                    self.$message({
                        type: 'info',
                        message: '已取消停用'
                    });          
                });
            },
            alldaochuClick(){
                let self = this;
                self.showLoading('操作中')
                let params = {
                  labourName:this.searchObj.representName,
                  phone:this.searchObj.phone,
                  identityCode:this.searchObj.identityCode
                }
                self.$axios({
                        method: 'post',
                        headers:{
                            Authorization:self.requestToken 
                        },
                        url: `/site/exportedList`,
                        responseType: 'blob',
                        data:params
                }).then(res => {
                    console.log(res);
                    self.hideLoading();
                        if(res.status == '200'){
                            let href = window.URL.createObjectURL(new Blob([res.data]));
                            let link = document.createElement('a');
                            link.style.display = 'none';
                            link.href = href;
                            link.setAttribute('download', "驻厂代表导出.xlsx");
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                            window.URL.revokeObjectURL(href);
                        }else{
                            self.$message.error(res.data.message)
                        }
                        
                }).catch(err=>{
                    self.hideLoading();
                    self.$message.error(err)
                })
            },
            // 新增
            addPolice(){
                let self = this;
                self.newaddFlag = true;
                self.initCompanyList();
            },
            initCompanyList(){
                let self = this;
                self.showLoading();
                self.$axios({
                    method: 'get',
                    url: `/site/queryInitAddLabourSite`,
                    headers:{
                        Authorization:self.requestToken     
                    }
                }).then(res => {
                    self.hideLoading();
                    if(res.data.code == '20000'){
                        self.bindingList = res.data.data.businessInfos;
                    }else{
                        self.$message.error(res.data.message)
                    }
                }).catch(err => {
                    self.hideLoading();
                    self.$message.error(err)
                })
            },
            // 详情
            detailsClick(row){
                this.detailsFlag = true;
            },
            // 详情关闭
            detailsClose(){
                this.detailsFlag = false;
            },
            // 修改
            editClick(row){
                let self = this;
                self.currentId = row.id;
                self.currentUserid = row.userId;
                self.initCompanyList();
                self.showLoading();
                self.$axios({
                    method: 'get',
                    url: `/site/queryInfoById/${row.id}`,
                    headers:{
                        Authorization:self.requestToken     
                    }
                }).then(res => {
                    self.hideLoading();
                    if(res.data.code == '20000'){
                        self.editFlag = true;
                        self.inputObj1.name = res.data.data.name;
                        self.inputObj1.identity = res.data.data.identity;
                        self.inputObj1.phone = res.data.data.phone;
                        self.bindValue = res.data.data.componentCodes;
                    }else{
                        self.$message.error(res.data.message)
                    }
                }).catch(err => {
                    self.hideLoading();
                    self.$message.error(err)
                })
            }
        }
    }
</script>
<style scoped>
  .common-title-flex{
      display:flex;
  }
  .common-title-div{
      width:3px;
      height:16px;
      background-color:#368af7;
      margin-top:2px;
  }
  .common-title-text{
      margin-left:4px;
      font-size: 14px;
  }
  .common-list-class{
      display:flex;
      justify-content:space-between;
      margin-top:-10px;
  }
  .upload-file >>> .el-upload--text{
      border:none;
      width: 100px;
      height: 36px;
  }
  .transfer-binding >>> .el-transfer-panel{
      width: 300px !important;
  }
</style>